const moment = require('moment')
const db = require('./db.js')

exports.getTopics = async (query) => {
	try {
		let {_page = 1, _limit = 2} = query

		if (_page < 1) {
			_page = 1
		}
		if (_limit < 1) {
			_limit = 1
		}
		if (_limit > 20) {
			_limit = 20
		}

		const _start = (_page - 1) * _limit
		const strSql = `
			select * from topics order by id desc limit ${_start} , ${_limit} 
		`
		return await db.query(strSql)
	} catch(err) {
		throw err
	}
}

exports.addTopic = async (body) => {
	try {
		const curTime = moment().format('YYYY-MM-DD hh:mm:ss')
		const strSql = `
			insert into topics (title,content,user_id,create_time,modify_time) 
			values(
				'${body.title}',
				'${body.content}',
				'${body.user_id}',
				'${curTime}',
				'${curTime}'
			)
		`
		const ret = await db.query(strSql)
		return ret.insertId
	} catch(err) {
		throw err
	}
}

exports.getTopic = async (id) => {
	try {
		const strSql = `
			select * from topics where id='${id}'
		`
		const [topic] = await db.query(strSql)
		return topic
	} catch(err) {
		throw err
	}
}